from PIL import Image, ImageDraw, ImageColor

def draw_rounded_gradient_deep_bar(
    score,
    width=400,
    height=40,
    radius=20,
    start_color="#7B61FF",  # Purple
    mid_color="#FF9BDB",    # Pink (currently used as end_color)
    end_color="#FF0000",    # Red
    bg_color="#e7d9f3"
):
    score = max(score, 10)
    # 创建仅包含进度条的画布（尺寸与进度条完全贴合）
    img = Image.new("RGBA", (width, height), color=(0, 0, 0, 0))
    draw = ImageDraw.Draw(img)
    # 1. 绘制进度条背景（完整圆角，底层）
    bg_rect = (0, 0, width-2, height)
    draw.rounded_rectangle(bg_rect, radius=radius, fill=bg_color)
    # 计算填充宽度（确保有效范围）
    fill_width = int(score / 100 * width)
    if fill_width <= 0:
        return img
    fill_width = min(fill_width, width)  # 限制最大宽度不超过进度条总宽
    # 2. 填充区域（直角矩形，配合反向圆角偏移）
    # radius 是预留一块  渐变长度 给左右多出来的半圆留位置
    fill_rect = (radius, 0, fill_width-12, height)
    # 3. 绘制平滑渐变填充
    # 3. 绘制平滑渐变填充（三色渐变）
    max_fill_width = int(100 / 100 * width)  # 最大填充宽度

    # 在渐变绘制部分修改为：
    for x in range(fill_rect[0], fill_rect[2]):
        # 使用整个进度条宽度作为基准计算比例
        ratio = (x - fill_rect[0]) / max_fill_width
        ratio = min(ratio, 1.0)  # 确保不超过1.0

        # 颜色过渡逻辑保持不变
        if ratio <= 0.5:  # 0%-50%: 紫色到粉色
            local_ratio = ratio * 2  # 映射到0-1
            base_color = ImageColor.getrgb(start_color)
            target_color = ImageColor.getrgb(mid_color)
        else:  # 50%-100%: 粉色到红色
            local_ratio = (ratio - 0.5) * 2  # 映射到0-1
            base_color = ImageColor.getrgb(mid_color)
            target_color = ImageColor.getrgb(end_color)

        # 颜色插值计算保持不变
        r = int(base_color[0] + local_ratio * (target_color[0] - base_color[0]))
        g = int(base_color[1] + local_ratio * (target_color[1] - base_color[1]))
        b = int(base_color[2] + local_ratio * (target_color[2] - base_color[2]))
        tail_color = (r, g, b)
        draw.rectangle((x, fill_rect[1], x + 1, fill_rect[3]), fill=(r, g, b))
    # 4. 绘制头部反向圆角（左侧）
    head_radius = min(radius, fill_width)
    if head_radius > 0:
        draw.pieslice(
            (fill_rect[0] - head_radius, 0,
             fill_rect[0] + head_radius, 2 * head_radius),
            start=90, end=270, fill=start_color
        )
    tail_radius = min(radius, fill_width)
    if tail_radius > 0:
        # 根据当前进度位置决定尾部圆角颜色
        draw.pieslice(
            (fill_rect[2] - tail_radius, height-2 * tail_radius,
             fill_rect[2] + tail_radius, height),
            start=270, end=90, fill=tail_color
        )
    return img

# 示例调用（仅传入分数，无文字相关参数）
score = 120
img = draw_rounded_gradient_deep_bar(score, width=600, height=20, radius=10)
img.save("img.png")